package org.example.controller;

import com.alibaba.excel.EasyExcel;
import org.example.domain.CarFile;
import org.example.listener.CarFileListener;
import org.example.service.CarFileService;
import org.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("CarFile")
@CrossOrigin
public class CarFileController {
    @Autowired
    CarFileService carFileService;
    @RequestMapping("list")
    public Result list(){
        List<CarFile> list=carFileService.list();
      return Result.success(list);
    }
    @RequestMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<CarFile> list=carFileService.lists();
        String fileName = CarFile.class.getSimpleName();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easy excel没有关系
        fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CarFile.class).sheet("模板").doWrite(list);
    }


    @RequestMapping("upload")
    public Map<String,Object> upload(MultipartFile file) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        try {
            map.put("code",200);
            EasyExcel.read(file.getInputStream(), CarFile.class, new CarFileListener(carFileService)).sheet().doRead();
        }catch (Exception e){
            map.put("code",500);
            e.printStackTrace();
        }
        return map;
    }
}
